#include <string.h>
#include <stdlib.h>
#include "configLoad.h"

int configCount=3;//there are 3 config lines

int loadConfigs(char const *filename,struct ConfigVars **data_ptr){
	FILE *ptr_file;///create FILE pointer
	ptr_file=fopen(filename,"r");///open file specified in *filename
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;///used to allocate buffer length
	int numlines=getFileInfo(ptr_file,&maxlinelen);///used to allocate configs array size
	struct ConfigVars *data;
	data=(struct ConfigVars*) calloc(numlines,sizeof(struct ConfigVars));///allocate config array
	char *buf=(char*) malloc(maxlinelen*sizeof(char));///allocate buffer size
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);///load a line to buffer
		data[i].setting_string=(char*) malloc(30*sizeof(char));
		strcpy(data[i].setting_string,strtok(buf,"-"));///get first token
		sscanf(strtok(NULL,"\n"), "%d", &data[i].value);
	}
	free(buf);
	fclose(ptr_file);
	*data_ptr=data;
	return 0;
}

int writeConfigs(char const *filename,struct ConfigVars *data){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	///loop through configs
	for(int i=0;i<configCount;i++){
		///print a line
		fprintf(ptr_file,"%s-%d\n",data[i].setting_string,data[i].value);
	}
	fclose(ptr_file);
	free(data);
	return 0;
}
